from django.shortcuts import render, redirect
from app02 import models


def depart_list(request):
    """ 部门列表 """
    #  去数据库获取所有部门列表
    queryset = models.Department.objects.all()

    return render(request, 'depart_list.html', {'queryset': queryset})


def depart_add(request):
    if request.method == 'GET':
        return render(request, 'depart_add.html')

    # 获取用户提交的数据(title输入为空)
    title = request.POST.get('title')

    # 保存到数据库
    models.Department.objects.create(title=title)
    return redirect("/depart/list/")


def depart_delete(request):
    """ 删除部门 """
    nid = request.GET.get('nid')
    models.Department.objects.filter(id=nid).delete()
    return redirect("/depart/list/")


def depart_edit(request, nid):
    """ 编辑部门 """
    # 根据nid，获取他的数据[obj,]
    if request.method == 'GET':
        row_obj = models.Department.objects.filter(id=nid).first()
        return render(request, "depart_edit.html", {"row_obj": row_obj})

    title = request.POST.get('title')
    models.Department.objects.filter(id=nid).update(title=title)
    return redirect("/depart/list/")